<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/6/9
  Time: 15:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>

<head>
    <title>员工列表页面</title>
</head>
<%
    pageContext.setAttribute("appPath",request.getContextPath());
%>
<script type="text/javascript" src="webjars/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="${appPath}/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
<script src="${appPath}/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
<body>


<!-- 员工的模态框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="save_form">
                    <div class="form-group">
                        <label for="add_empName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="add_empName" placeholder="姓名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_email" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="add_email" placeholder="2080448699@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2" value="F"> 女
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label  class="col-sm-2 control-label">Department</label>
                        <div class="col-sm-4">
                            <select  class="form-control" name="dId" id="dept_select">

                            </select>
                        </div>
                    </div>


                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="btn_save">保存</button>
            </div>
        </div>
    </div>
</div>
<%--员工修改的模态框--%>
<div class="modal fade" id="myUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="update_form">
                    <div class="form-group">
                        <label for="add_empName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="update_empName"></p>

                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="add_email" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="update_email" placeholder="email@atguigu.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="update_gender1" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="update_gender2" value="F"> 女
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label  class="col-sm-2 control-label">Department</label>
                        <div class="col-sm-4">
                            <select  class="form-control" name="dId" id="update_dept_select">

                            </select>
                        </div>
                    </div>


                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="update_btn_save">修改</button>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-12"><h1>SSM-CRUD</h1></div>
    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button type="button" class="btn btn-primary" id="emps_add">新增</button>
            <button type="button" class="btn btn-danger" id="emps_delete">删除</button>
        </div>

    </div>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead> <tr>
                    <th>
                        <input type="checkbox" id="check_all">
                    </th>
                    <th>#</th>
                    <th>lastName</th>
                    <th>email</th>
                    <th>gender</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr></thead>

                <tbody>

                </tbody>


            </table>

        </div>
    </div>
    <div class="row">
        <%--字体信息--%>
        <div class="col-lg-6" id="showMessage_area">

        </div>
        <%--分隔条--%>
        <div class="col-lg-6" id="showPagInfo_area">

        </div>

    </div>


</div>
<script type="text/javascript">
    var finalTotal,NowPage;
    $(function (){
        //去首页
        to_page(1);
    });

    //抽取成跳转方法ajax
    function to_page(pn){
        $.ajax({
            url:"${appPath}/emps",
            data:"pn="+pn,
            type:"GET",
            success:function (result){
                // console.log(result);
                //解析并展示员工
                buildTable(result);
                //显示分页数据
                showMessage(result);
                //显示分页条
                showPageInfo(result);
            }

        });
    }


    //解析并构件表格的
    function buildTable(result){
        //清空上次数据
        $("#emps_table tbody").empty();

        var emps = result.extend.pageInfo.list;
        $.each(emps,function (index,item){

            var checkBox = $("  <td><input type='checkbox' class='check_item'></td>")
            var empIdTd = $("<td></td>").append(item.empId);
            var empNameTd = $("<td></td>").append(item.empName);
            var genderTd = $("<td></td>").append(item.gender == "M"?"男":"女");
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTd = $("<td></td>").append(item.department.deptName);
            /*<button type="button" class="btn btn-primary btn-sm">
                            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>新增</button>
                            <button type="button" class="btn btn-danger btn-sm">
                                <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除</button>*/
            var edit_btn = $("<button></button>").
            addClass("btn btn-primary btn-sm edit_btn").
            append("<span></span>").addClass("glyphicon glyphicon-pencil").append("编辑");
            //给修改和删除按钮添加一个属性用来标记传入的员工id
            edit_btn.attr("edit_id",item.empId);


            var delete_btn = $("<button></button>").
            addClass("btn btn-danger btn-sm delete_btn").
            append("<span></span>").addClass("glyphicon glyphicon-trash").append("删除");

            var btn_td = $("<td></td>").append(edit_btn).append(" ").append(delete_btn);


               $("<tr></tr>").append(checkBox).append(empIdTd).
               append(empNameTd).append(emailTd).append(genderTd).append(deptNameTd)
                 .append(btn_td).appendTo("#emps_table tbody");
               delete_btn.attr("delete_id",item.empId)
        })
    }

    //解析显示页码数据信息的
   function showMessage(result){
      $("#showMessage_area").empty();
        $("#showMessage_area").append("  当前第"+result.extend.pageInfo.pageNum+"页,总页码"
            +result.extend.pageInfo.pages+",总记录数条"+result.extend.pageInfo.total+"")
       finalTotal = result.extend.pageInfo.total;
        NowPage = result.extend.pageInfo.pageNum;

   }
    //解析显示分页条
    function showPageInfo(result){
        //分页条清空
        $("#showPagInfo_area").empty();
        /*
            <li>
                  <a href="#" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                  </a>
            </li>*/

        /*<ul class="pagination">*/

        var UL = $("<ul></ul>").addClass("pagination");
        var btn_firstPage = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("首页")));
        var btn_prePage = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if (result.extend.pageInfo.hasPreviousPage == false){
            btn_firstPage.addClass("disabled");
            btn_prePage.addClass("disabled");
        }else {
            //为构建的按钮添加跳转
            //首页
            btn_firstPage.click(function (){
                to_page(1);
            });
            btn_prePage.click(function (){
                to_page(result.extend.pageInfo.tprePage);
            });
        }


      /*  //前一页
        prePage.cilck(function(){
            to_page(result.extend.pageInfo.prePage);
        });*/
        var btn_nextPage = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var btn_lastPage = $("<li></li>").append($("<a></a>").attr("href","#").append($("<span></span>").append("末页")));
        if (result.extend.pageInfo.hasNextPage == false){
            btn_nextPage.addClass("disabled");
            btn_lastPage.addClass("disabled");
        }else {
            btn_nextPage.click(function (){
                to_page(result.extend.pageInfo.nextPage);
            });
            btn_lastPage.click(function (){
                to_page(result.extend.pageInfo.pages);
            });
        }

        //拼接首页和前一页
        UL.append(btn_firstPage).append(btn_prePage);
        //遍历并添加的分页
        $.each(result.extend.pageInfo.navigatepageNums,function (index,item){
            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if (result.extend.pageInfo.pageNum == item){
                numLi.addClass("active");
            }
            //给分页按钮添加跳转事件
            numLi.click(function (){
                to_page(item);
            });
            UL.append(numLi);
        });
        //拼接末页和下一页
        UL.append(btn_nextPage).append(btn_lastPage);
        //拼接到nav里面
        var navTL = $("<nav></nav>").append(UL);
        navTL.appendTo("#showPagInfo_area");


    }
    //清空表单样式和内容
    function cleanAll(ele){
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-success has-error");
        $(ele).find(".help-block").text("");
    }
                //点击新增弹出模态框
                $("#emps_add").click(function (){
                    //保存前清空表单内容防止跳过ajax校验(表单重置)
                    cleanAll("#myModal form")


                    //1. 1.弹出前向数据库发请求获取部门
                        getDepts("#dept_select");

                    //2.展示模态框
                    $("#myModal").modal({
                        backdrop:"static"
                    })
                });
    //获取数据库中的部门表,然后展示在模态框中
    function getDepts(ele){
    //需要清除
        $(ele).empty();
        $.ajax({
            url:"${appPath}/depts",
            type:"GET",
            success:function (result){
                /*{"code":200,"msg":"处理成功!",
                "extend":{"dept":[{"deptId":1,"deptName":"开发部"},{"deptId":2,"deptName":"测试部"}]}}*/
                //console.log(result);
                $.each(result.extend.dept,function (){
                    var dept_select = $("<option></option>").append(this.deptName).attr("value",this.deptId);
                    dept_select.appendTo(ele);
                });
            }
        });
    }

    //校验方法
    function check_validate_from(){
        var empName_test = $("#add_empName").val();
        var empName_reg =/(^[a-zA-Z0-9_-]{3,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        //校验用户名
        if ( !empName_reg.test(empName_test)){
            //alert("用户名格式错误");
            nameAndEmail("#add_empName","error","用户名格式错误,要6到16位的数字组合，或2到5个汉字");
            return false;
        }else {
            nameAndEmail("#add_empName","success","");
        }
        var email_test = $("#add_email").val();
        var email_reg =/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{1,56})$/
        //校验email
        if ( !email_reg.test(email_test)){
            //alert("邮箱格式错误");
            nameAndEmail("#add_email","error","邮箱错误")
            return false;
        }else{
            nameAndEmail("#add_email","success","")
        }
        return true;
    }
    //校验抽取
    function nameAndEmail(ele,status,msg){
        //清除当前元素的校验状态
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if("success"==status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        }else if("error" == status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }
    //校验用户名，和email是否重复
    $("#add_empName").change(function (){
        //发送ajax请求校验是否成功
        var empName =  this.value;
        $.ajax({
            url:"${appPath}/checkUser",
            type:"POST",
            data:"empName="+empName,
            success:function (result){
                    if (result.code == 200){
                        nameAndEmail("#add_empName","success","用户名可用");
                        $("#btn_save").attr("ajax_tv","success")
                    }else {
                        nameAndEmail("#add_empName","error",result.extend.va_msg);
                        $("#btn_save").attr("ajax_tv","error")
                    }
            }
        });
    });

    //员工保存
    $("#btn_save").click(function (){


        //保存前先校验
        if (!check_validate_from()){
            return false;
        }
        //存入校验
        if ($(this).attr("ajax_tv") == "error"){
            return false;
        }
        $.ajax({
            url:"${appPath}/emp",
            type:"POST",
            data:$("#save_form").serialize(),
            success:function (result){
                //303校验保存
                if (result.code == 200){
                    //保存成功后关闭框
                    $('#myModal').modal('hide')
                    //且跳转最后面查看
                    to_page(finalTotal);
                }else {
                    //显示失败信息
                    //console.log(result);
                  /*  {code: 400, msg: "处理失败!", extend: {…}}
                    code: 400
                    extend:
                        errorMap:
                            email: "303校验邮箱错误"
                    __proto__:
                        constructor: ƒ Object()
                    hasOwnProperty: ƒ hasOwnProperty()
                    isPrototypeOf: ƒ isPrototypeOf()
                    propertyIsEnumerable: ƒ propertyIsEnumerable()
                    toLocaleStrin*/

                    if (undefined !=result.extend.errorMap.email){
                            //显示邮箱错误
                        nameAndEmail("#add_email","error",result.extend.errorMap.email)
                    }
                    if (undefined !=result.extend.errorMap.empName){
                        nameAndEmail("#add_empName","error",result.extend.errorMap.empName);
                    }
                }

        }
        });
    });
    //给编辑按钮添加弹出模态框
    //由于这里的事件的绑定是有ajax请求的，所以事件的绑定在按钮被创建之前就运行，导致绑定不成功，所以我们采用事件的委派，
    //中的live方法，但是新版的jquery将live删除，用on代替
    $(document).on("click",".edit_btn ",function (){
        //获取员工部门信息

        getDepts("#myUpdateModal select");
        //获取员工信息
           getEmp($(this).attr("edit_id"));
        //给模态框的保存修改的按钮传id
        $("#update_btn_save").attr("edit_id",$(this).attr("edit_id"))
        //2.展示模态框
        $("#myUpdateModal").modal({
            backdrop:"static"
        })
    });
    //查询员工信息
    function getEmp(id){
        $.ajax({
            url:"${appPath}/emp/"+id,
            type:"GET",
            success:function (result){
                // console.log(result);
                var empData =result.extend.emp;
             $("#update_empName").text(empData.empName);
             $("#update_email").text(empData.email);
             $("#myUpdateModal input[name= gender]").val([empData.gender]);
             $("#myUpdateModal select").val([empData.dId])
            }
        });
    }
    //给修改按钮添加点击事件
    $("#update_btn_save").click(function () {
        //点击修改之前先校验邮箱
        var email_test = $("#update_email").val();
        var email_reg =/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{1,56})$/
        //校验email
        if ( !email_reg.test(email_test)){
            //alert("邮箱格式错误");
            nameAndEmail("#update_email","error","邮箱错误")
            return false;
        }else{
            nameAndEmail("#update_email","success","")
        }
        //发送ajax请求保存修改的员工信息
        $.ajax({
            url:"${appPath}/emp/"+$(this).attr("edit_id"),
            type:"PUT",
            data:$("#myUpdateModal form").serialize(),
            success:function (result){
                console.log(result);
                //关闭，框
                //保存成功后关闭框
                $('#myUpdateModal').modal('hide')
                //且跳转最后面查看
                to_page(NowPage);
            }
        });
    });
    //给删除按钮添加功能
    $(document).on("click",".delete_btn",function (){
        var name = $(this).parents("tr").find("td:eq(2)").text()
       //alert($(this).parents("tr").find("td:eq(1)").text());
        //弹出对话框
        if (confirm("确认删除"+name+"员工吗")){
            //确认即可，发送ajax请求
            $.ajax({
                url:"${appPath}/emp/"+$(this).attr("delete_id"),
                type:"DELETE",
                success:function (result){
                    to_page(NowPage);
                }

            });
        }
    });
    //给全选按钮添加全选功能
    $("#check_all").click(function (){
        //当它被选中时，我们将所有的的class属性的checkBox都与之同步
        // alert($("#check_all").prop("checked"));
        $(".check_item").prop("checked",$("#check_all").prop("checked"));
    });
    //当页面的其他按钮都被全选之后,将全选按钮值为被选状态
    //
    $(document).on("click",".check_item",function (){
        var flag = $(".check_item:checked").length ==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    });

    //给批量删按钮添加删功能
    $("#emps_delete").click(function (){
       //当全删按钮被点击时，获取所有被选中的框
        var empNames ="";
        var empIds = "";
        $.each($(".check_item:checked"),function (){
            empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
            empIds +=  $(this).parents("tr").find("td:eq(1)").text()+"-";

        });
        empNames = empNames.substring(0,empNames.length-1);
        empIds = empIds.substring(0,empIds.length-1);
        if (confirm("确定删除"+empNames+"吗")){
            //然后删除,发送ajax请求
            $.ajax({
                url:"${appPath}/emp/"+empIds,
                type:"DELETE",
                success:function (result){
                    to_page(NowPage);
                }
            });

        }

    });






</script>

</body>
</html>
